<template>
  <div class="community-list">

    <!-- 搜索区域 + 新增按钮放一行 -->
    <div class="row mb-3 align-items-center" style="margin-bottom: 20px;">
      <!-- 左侧：搜索相关 -->
      <div class="col-sm-9">
        <form class="form-inline search-row">
          <div class="form-group" style="margin-right: 1rem;">
            <input v-model="searchForm.keyWords"
                   type="text"
                   class="form-control"
                   placeholder="小区名称" />
          </div>
          <div class="form-group" style="margin-right: 1rem;">
            <select v-model="searchForm.areaId" class="form-control" @change="handleAreaChange">
              <option value="">-请选择区域-</option>
              <option v-for="area in areaList" :key="area.id" :value="area.id">{{ area.name }}</option>
            </select>
          </div>
          <div class="form-group" style="margin-right: 1rem;">
            <select v-model="searchForm.plateId" class="form-control">
              <option value="">-请选择板块-</option>
              <option v-for="plate in plateList" :key="plate.id" :value="plate.id">{{ plate.name }}</option>
            </select>
          </div>
          <button class="btn btn-search btn-sm" type="button" @click="fetchData(1)">搜索</button>
        </form>
      </div>
      <!-- 右侧：新增按钮 靠右 -->
      <div class="col-sm-3 text-right">
        <button class="btn btn-create btn-sm" @click="handleCreate" style="margin-top:15px;">
          新增小区
        </button>
      </div>
    </div>


    <!-- 3. 数据表格 -->
    <table class="table table-striped table-bordered table-hover">
      <thead>
      <tr>
        <th>序号</th>
        <th>小区名称</th>
        <th>区域</th>
        <th>板块</th>
        <th>详细地址</th>
        <th>建筑年代</th>
        <th>创建时间</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="(item, idx) in tableData" :key="item.id">
        <td>{{(pageNum - 1) * pageSize + idx + 1}}</td>
        <td>{{ item.name }}</td>
        <td>{{ item.areaName }}</td>
        <td>{{ item.plateName }}</td>
        <td>{{ item.address }}</td>
        <td>{{ item.build_years }}</td>
        <td>{{ formatDate(item.create_time) }}</td>
        <td class="action-cell">
          <a href="#" @click.prevent="handleEdit(item)">修改</a>
          <a href="#" class="text-danger" @click.prevent="handleDelete(item)">删除</a>
        </td>
      </tr>
      <tr v-if="tableData.length === 0">
        <td colspan="8" class="text-center">暂无数据</td>
      </tr>
      </tbody>
    </table>

    <!-- 4. 分页栏 -->
    <div class="row align-items-center">
      <div class="col-sm-6">
        <small>当前第 {{ pageNum }} 页 / 共 {{ totalPage }} 页 共 {{ totalSize }} 条记录</small>
      </div>
      <div class="col-sm-6 text-right">
        <ul class="pagination mb-0 justify-content-end">
          <li class="page-item" :class="{ disabled: pageNum <= 1 }">
            <a class="page-link" href="#" @click.prevent="fetchData(1)">第一页</a>
          </li>
          <li class="page-item" :class="{ disabled: pageNum <= 1 }">
            <a class="page-link" href="#" @click.prevent="fetchData(pageNum - 1)">上一页</a>
          </li>

          <!-- 动态生成所有页码按钮 -->
          <li
              class="page-item"
              v-for="n in totalPage"
              :key="n"
              :class="{ active: pageNum === n }"
          >
            <a class="page-link" href="#" @click.prevent="fetchData(n)">
              {{ n }}
            </a>
          </li>

          <li class="page-item" :class="{ disabled: pageNum >= totalPage }">
            <a class="page-link" href="#" @click.prevent="fetchData(pageNum + 1)">下一页</a>
          </li>
          <li class="page-item" :class="{ disabled: pageNum >= totalPage }">
            <a class="page-link" href="#" @click.prevent="fetchData(totalPage)">尾页</a>
          </li>
        </ul>
      </div>
    </div>
  </div>

  <!-- 创建弹窗组件 -->
  <CreateCommunity ref="createRef" @saved="fetchData(1)" />
  <EditCommunity   ref="editRef"   @saved="fetchData(1)" />
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
// 导入新增按钮对应的新增页面
import CreateCommunity from './CreateCommunity.vue'
// 导入修改按钮对应的修改页面
import EditCommunity  from './EditCommunity.vue'

// 搜索功能的请求参数
const searchForm = ref({
  keyWords: '',
  areaId: '',
  plateId: ''
})


// 数据
const tableData = ref([])
const areaList = ref([])
const plateList = ref([])

// 分页参数
const pageNum = ref(1)
const pageSize = ref(10)
const totalSize = ref(0)

// 计算总页数
const totalPage = computed(() => {
  return Math.ceil(totalSize.value / pageSize.value) || 1
})

// 工具：格式化日期
function formatDate(dt) {
  return dt ? dt.split('T')[0] : ''
}


// 取区域列表（beijing）
// 先写死，假设是 beijing 地区
let areaDictCode = "beijing"

async function fetchAreaList() {
  try {
    // 模板字符串拼接语法
    const res = await axios.get(
        `/app-dev/community/findDictListByParentDictCode/${areaDictCode}`
    )
    if (res.data.code === 200) {
      areaList.value = res.data.data
    } else {
      ElMessage.error('加载区域失败：' + res.data.message)
    }
  } catch (err) {
    ElMessage.error('网络异常，加载区域失败')
  }
}

// 区域改变后拿对应板块
async function handleAreaChange () {
  const pid = searchForm.value.areaId
  // 清空板块
  plateList.value = []
  searchForm.value.plateId = ''

  if (!pid) return        // “请选择区域”时直接返回

  try {
    const res = await axios.get(
        `/app-dev/community/findDictListByParentId/${pid}`
    )
    if (res.data.code === 200) {
      plateList.value = res.data.data
    } else {
      ElMessage.error('加载板块失败：' + res.data.message)
    }
  } catch (e) {
    ElMessage.error('网络异常，加载板块失败')
  }
}


// 显示分页数据
async function fetchData(page = 1) {
  pageNum.value = page
  const params = {
    ...searchForm.value,
    pageNum: pageNum.value,
    pageSize: pageSize.value
  }
  // 向后端发送 ajax 请求
  const res = await axios.post('/app-dev/community', params)
  // 获取后端响应数据
  if (res.data?.code === 200) {
    tableData.value = res.data.data.pageData || []
    totalSize.value = res.data.data.totalSize || 0
  } else {
    ElMessage.error(res.data.message || '查询失败')
  }
}

// 点击新增按钮，弹框中显示新增页面
const createRef = ref(null)
function handleCreate () {
  createRef.value.openModal(areaList.value)
}

// 点击修改按钮，弹窗中显示修改页面
const editRef   = ref(null)
function handleEdit (row) {
  editRef.value.openModal(row.id, areaList.value)  // 传 id + 区域列表
}

// 点击删除按钮，确认删除
async function handleDelete (row) {
  try {
    /* 1. 二次确认 */
    await ElMessageBox.confirm(
        `确定要删除【${row.name}】吗？`,         // 提示文字
        '提示',                                  // 标题
        { confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' }
    )
    /* 2. 调用后端逻辑删除接口 */
    const { data } = await axios.get(`/app-dev/community/delete/${row.id}`)
    if (data.code === 200) {
      ElMessage.success('删除成功')
      fetchData(pageNum.value)                 // 刷新当前页
    } else {
      ElMessage.error(data.message || '删除失败')
    }
  } catch (err) {
    // 如果是点击“取消”会抛 reject，直接静默即可
  }
}

onMounted(() => {
  fetchAreaList()
  fetchData()
})
</script>

<style scoped>
.community-list {
  padding: 24px 22px 3px 12px;  /* 上右下左 */
}

/* 操作列：修改，删除等链接的间隙 */
.action-cell a {
  margin-right: 0.5rem;
}

/* 缩小按钮尺寸 */
.btn-sm {
  padding: 0.25rem 0.6rem;
  font-size: 1.2rem;
  line-height: 1.2;
}

/* 搜索行底部间距 */
.search-row {
  margin-bottom: 0;
}

/* 自定义按钮颜色 */
.btn-search {
  background-color: rgba(0, 123, 255, 0.97);
  border-color: rgb(0, 123, 255);
  color: #fff;
}
.btn-search:hover {
  background-color: rgb(175, 208, 243);
  border-color: rgb(203, 224, 250);
  color: #fff;
}

.btn-create {
  background-color: rgba(0, 123, 255, 0.97);
  border-color: rgb(0, 123, 255);
  color: #fff;
}
.btn-create:hover {
  background-color: rgb(175, 208, 243);
  border-color: rgb(203, 224, 250);
  color: #fff;
}
</style>

